import { ethers } from 'ethers';
import CryptoJS from 'crypto-js';

export interface WalletAccount {
  address: string;
  privateKey: string;
  publicKey: string;
  name: string;
  balance: string;
  network: string;
}

export interface Transaction {
  hash: string;
  from: string;
  to: string;
  value: string;
  gasPrice: string;
  gasLimit: string;
  nonce: number;
  timestamp: number;
  status: 'pending' | 'confirmed' | 'failed';
}

export class WalletManager {
  private accounts: WalletAccount[] = [];
  private currentAccount: WalletAccount | null = null;
  private provider: ethers.JsonRpcProvider | null = null;

  constructor() {
    this.loadAccounts();
  }

  // 创建新钱包
  async createWallet(name: string, password: string): Promise<WalletAccount> {
    const wallet = ethers.Wallet.createRandom();
    const account: WalletAccount = {
      address: wallet.address,
      privateKey: wallet.privateKey,
      publicKey: wallet.publicKey,
      name,
      balance: '0',
      network: 'ethereum'
    };

    // 加密私钥
    const encryptedPrivateKey = this.encryptPrivateKey(account.privateKey, password);
    account.privateKey = encryptedPrivateKey;

    this.accounts.push(account);
    await this.saveAccounts();
    
    return account;
  }

  // 导入钱包
  async importWallet(privateKey: string, name: string, password: string): Promise<WalletAccount> {
    const wallet = new ethers.Wallet(privateKey);
    const account: WalletAccount = {
      address: wallet.address,
      privateKey: this.encryptPrivateKey(privateKey, password),
      publicKey: wallet.publicKey,
      name,
      balance: '0',
      network: 'ethereum'
    };

    this.accounts.push(account);
    await this.saveAccounts();
    
    return account;
  }

  // 解锁钱包
  async unlockWallet(address: string, password: string): Promise<boolean> {
    const account = this.accounts.find(acc => acc.address === address);
    if (!account) return false;

    try {
      const decryptedPrivateKey = this.decryptPrivateKey(account.privateKey, password);
      const wallet = new ethers.Wallet(decryptedPrivateKey);
      
      if (wallet.address === address) {
        this.currentAccount = account;
        return true;
      }
    } catch (error) {
      console.error('解锁钱包失败:', error);
    }
    
    return false;
  }

  // 获取账户余额
  async getBalance(address: string): Promise<string> {
    if (!this.provider) {
      this.provider = new ethers.JsonRpcProvider('https://mainnet.infura.io/v3/YOUR_INFURA_KEY');
    }

    try {
      const balance = await this.provider.getBalance(address);
      return ethers.formatEther(balance);
    } catch (error) {
      console.error('获取余额失败:', error);
      return '0';
    }
  }

  // 发送交易
  async sendTransaction(to: string, amount: string, password: string): Promise<string> {
    if (!this.currentAccount) {
      throw new Error('请先解锁钱包');
    }

    const decryptedPrivateKey = this.decryptPrivateKey(this.currentAccount.privateKey, password);
    const wallet = new ethers.Wallet(decryptedPrivateKey, this.provider);

    try {
      const tx = await wallet.sendTransaction({
        to,
        value: ethers.parseEther(amount)
      });

      return tx.hash;
    } catch (error) {
      console.error('发送交易失败:', error);
      throw error;
    }
  }

  // 加密私钥
  private encryptPrivateKey(privateKey: string, password: string): string {
    return CryptoJS.AES.encrypt(privateKey, password).toString();
  }

  // 解密私钥
  private decryptPrivateKey(encryptedPrivateKey: string, password: string): string {
    const bytes = CryptoJS.AES.decrypt(encryptedPrivateKey, password);
    return bytes.toString(CryptoJS.enc.Utf8);
  }

  // 保存账户到本地存储
  private async saveAccounts(): Promise<void> {
    const accountsData = this.accounts.map(acc => ({
      ...acc,
      privateKey: acc.privateKey // 已经是加密的
    }));
    
    await chrome.storage.local.set({ accounts: accountsData });
  }

  // 从本地存储加载账户
  private async loadAccounts(): Promise<void> {
    const result = await chrome.storage.local.get(['accounts']);
    if (result.accounts) {
      this.accounts = result.accounts;
    }
  }

  // 获取所有账户
  getAccounts(): WalletAccount[] {
    return this.accounts.map(acc => ({
      ...acc,
      privateKey: '***' // 不返回真实私钥
    }));
  }

  // 获取当前账户
  getCurrentAccount(): WalletAccount | null {
    return this.currentAccount ? {
      ...this.currentAccount,
      privateKey: '***'
    } : null;
  }

  // 切换账户
  switchAccount(address: string): boolean {
    const account = this.accounts.find(acc => acc.address === address);
    if (account) {
      this.currentAccount = account;
      return true;
    }
    return false;
  }
}
